package com.nsgf.library.ui.page;

import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.DutyManagerBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityDutyRecordBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.matisse.MimeType;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 值班记录页面
 */
public class DutyRecordActivity extends BaseActivity {

    DutyRecordStates states;
    private ActivityDutyRecordBinding mBinding;
    private AccountRequester mAccountRequester;

    private int selectedWeatherIndex = 0; // 0-晴 1-阴 2-雨 3-雪
    private List<WeatherBean.DataBean> weatherList = new ArrayList<>(); // 天气列表数据
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private Calendar currentDate;
    private String selectedDateStr; // 从Intent传入的日期字符串
    private static final int REQUEST_CODE_PERSONNEL_SELECTION = 100;
    private static final int REQUEST_CODE_VIDEO = 1001; // 视频选择请求码
    private List<WorkOrderDetailBean.FileDto> selectedVideos = new ArrayList<>(); // 已选择的视频列表
    private String currentSelectionType; // 当前选择类型：dutyPerson, dutyLeader, handoverPerson, etc.

    @Override
    protected void initViewModel() {
        states = getActivityScopeViewModel(DutyRecordStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_duty_record, BR.vm, states)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityDutyRecordBinding) getBinding();

        if (getIntent() != null) {
            selectedDateStr = getIntent().getStringExtra("selectedDate");
            // 检查是否有传递的记录数据
            states.passedRecord.set((DutyManagerBean) getIntent().getSerializableExtra("dutyRecordData"));
            currentDate = Calendar.getInstance();
        } else {
            currentDate = Calendar.getInstance();
        }

        states.dutyDate.set(Kits.Date.getYmd(currentDate.getTimeInMillis()));

        // 如果有传入的记录数据，直接填充
        fillDataFromBean(states.passedRecord.get());

        initTitleBar();
        initObserver();
        // 初始化图片选择器
        initImagePicker();
    }

    /**
     * 初始化观察者
     */
    private void initObserver() {
        getLifecycle().addObserver(mAccountRequester);
        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> responseStatus) {
                if (responseStatus != null) {
                    if (responseStatus.getResponseCode() == 200) {
                        ToastUtils.showLongToast("保存成功");
                        finish();
                    } else {
                        ToastUtils.showLongToast(responseStatus.getMsg() != null ? responseStatus.getMsg() : "保存失败");
                    }
                }
            }
        });

        // 监听天气数据
        mAccountRequester.getWeatherDetailResult().observe(this, new Observer<DataResult<WeatherBean>>() {
            @Override
            public void onChanged(DataResult<WeatherBean> dataResult) {
                if (dataResult.getResult().getCode() == 200) {
                    if (dataResult.getResult().getData() != null) {
                        weatherList = dataResult.getResult().getData();
                        android.util.Log.d("DutyRecord", "天气数据加载成功，数量: " + weatherList.size());
                    }
                }
            }
        });
    }

    /**
     * 填充Bean数据到表单
     */
    private void fillDataFromBean(DutyManagerBean dutyBean) {
        if (dutyBean == null) {
            return;
        }

        // 如果BuSchedulingList中有人员信息，同时填充显示名称和对象列表
        if (dutyBean.getBuSchedulingList() != null && !dutyBean.getBuSchedulingList().isEmpty()) {
            // 分别处理非领导人员和领导人员
            List<DutyManagerBean.BuSchedulingListBean> personList = new ArrayList<>();
            List<DutyManagerBean.BuSchedulingListBean> leaderList = new ArrayList<>();

            StringBuilder personNames = new StringBuilder();
            StringBuilder leaderNames = new StringBuilder();

            for (DutyManagerBean.BuSchedulingListBean bean : dutyBean.getBuSchedulingList()) {
                if (bean.getIsLeader() == 1) {
                    // 领导人员
                    leaderList.add(bean);
                    if (leaderNames.length() > 0) {
                        leaderNames.append(",");
                    }
                    String leaderName = bean.getRealName() != null && !bean.getRealName().isEmpty()
                            ? bean.getRealName() : bean.getUserName();
                    if (leaderName != null && !leaderName.isEmpty()) {
                        leaderNames.append(leaderName);
                    }
                } else {
                    // 非领导人员
                    personList.add(bean);
                    if (personNames.length() > 0) {
                        personNames.append(",");
                    }
                    String personName = bean.getRealName() != null && !bean.getRealName().isEmpty()
                            ? bean.getRealName() : bean.getUserName();
                    if (personName != null && !personName.isEmpty()) {
                        personNames.append(personName);
                    }
                }
            }

            // 同时填充所有6组数据：显示名称和对象列表
            String personNamesStr = personNames.toString();
            String leaderNamesStr = leaderNames.toString();

            // 交班人员（handoverPerson 和 handoverPersonList）
            if (!personList.isEmpty()) {
                states.handoverPerson.set(personNamesStr);
                states.handoverPersonList.set(new ArrayList<>(personList));
            }

            // 交班领导（handoverLeader 和 handoverLeaderList）
            if (!leaderList.isEmpty()) {
                states.handoverLeader.set(leaderNamesStr);
                states.handoverLeaderList.set(new ArrayList<>(leaderList));
            }

            // 值班人员（dutyPerson 和 dutyPersonList）
            if (!personList.isEmpty()) {
                states.dutyPerson.set(personNamesStr);
                states.dutyPersonList.set(new ArrayList<>(personList));
            }

            // 值班领导（dutyLeader 和 dutyLeaderList）
            if (!leaderList.isEmpty()) {
                states.dutyLeader.set(leaderNamesStr);
                states.dutyLeaderList.set(new ArrayList<>(leaderList));
            }

        } else {
            // 如果没有BuSchedulingList，使用userName和leaderName作为后备方案
            // 填充值班人员信息
            if (dutyBean.getUserName() != null && !dutyBean.getUserName().isEmpty()) {
                states.dutyPerson.set(dutyBean.getUserName());
                states.handoverPerson.set(dutyBean.getUserName());
                states.receivingPerson.set(dutyBean.getUserName());
            }

            // 填充值班领导信息
            if (dutyBean.getLeaderName() != null && !dutyBean.getLeaderName().isEmpty()) {
                states.handoverLeader.set(dutyBean.getLeaderName());
                states.dutyLeader.set(dutyBean.getLeaderName());
                states.receivingLeader.set(dutyBean.getLeaderName());
            }
        }

        // TODO: 如果DutyManagerBean包含库水位、雨量等信息，在这里填充
        // states.waterLevel.set(dutyBean.getWaterLevel());
        // states.rainfall.set(dutyBean.getRainfall());

        // TODO: 填充其他数据
    }

    /**
     * 初始化标题栏
     */
    private void initTitleBar() {
        states.titleBar.set("交接班");
    }

    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        boolean[] type = new boolean[]{true, true, true, false, false, false};

        TimePickerView mTimePickerView = new TimePickerView.Builder(this, (date, v) -> {
            currentDate.setTime(date);
            states.dutyDate.set(dateFormat.format(date));
        })
                .isCyclic(false)
                .setRangDate(null, null)
                .setType(type)
                .setTitleText("选择日期")
                .setDate(currentDate)
                .build();

        mTimePickerView.show();
    }


    /**
     * 提交巡查记录
     */
    private void submitUpdate() {

        // 收集需要上传的文件（只上传本地路径的文件，跳过已经是http的）
        List<FileInfo> filesToUpload = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedPhotos = new ArrayList<>();
        List<WorkOrderDetailBean.FileDto> uploadedVideos = new ArrayList<>();

        // 视频文件大小限制：50MB
        final long MAX_VIDEO_SIZE = 50 * 1024 * 1024; // 50MB
        // 图片文件大小限制：10MB
        final long MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB

        // 收集图片文件
        if (mBinding.multiPickResultView.getPhotos() != null) {
            for (WorkOrderDetailBean.FileDto photo : mBinding.multiPickResultView.getPhotos()) {
                if (photo != null && photo.getFilePath() != null) {
                    if (photo.getFilePath().startsWith("http")) {
                        // 已经是服务器路径，直接添加到已上传列表
                        uploadedPhotos.add(photo);
                    } else {
                        // 检查图片文件大小
                        java.io.File photoFile = new java.io.File(photo.getFilePath());
                        if (photoFile.exists()) {
                            long fileSize = photoFile.length();
                            if (fileSize > MAX_IMAGE_SIZE) {
                                double sizeInMB = fileSize / (1024.0 * 1024.0);
                                ToastUtils.showLongToast(String.format("图片文件过大（%.2fMB），最大支持10MB", sizeInMB));
                                return;
                            }
                        }
                        // 本地路径，需要上传
                        filesToUpload.add(new FileInfo(photo.getFilePath(), true));
                    }
                }
            }
        }

        // 收集视频文件
        if (selectedVideos != null && !selectedVideos.isEmpty()) {
            for (WorkOrderDetailBean.FileDto video : selectedVideos) {
                if (video != null && video.getFilePath() != null) {
                    if (video.getFilePath().startsWith("http")) {
                        // 已经是服务器路径，直接添加到已上传列表
                        uploadedVideos.add(video);
                    } else {
                        // 检查视频文件大小
                        java.io.File videoFile = new java.io.File(video.getFilePath());
                        if (videoFile.exists()) {
                            long fileSize = videoFile.length();
                            if (fileSize > MAX_VIDEO_SIZE) {
                                double sizeInMB = fileSize / (1024.0 * 1024.0);
                                ToastUtils.showLongToast(String.format("视频文件过大（%.2fMB），最大支持50MB，请选择较小的视频", sizeInMB));
                                return;
                            }
                        }
                        // 本地路径，需要上传
                        filesToUpload.add(new FileInfo(video.getFilePath(), false));
                    }
                }
            }
        }

        // 如果有文件需要上传，先批量上传
        if (!filesToUpload.isEmpty()) {
            uploadFilesAndSubmit(filesToUpload, uploadedPhotos, uploadedVideos);
        } else {
            // 没有文件需要上传，直接提交
            onSubmit(null, null);
        }
    }


    /**
     * 文件信息类，用于记录文件路径和类型
     */
    private static class FileInfo {
        String filePath;
        boolean isPhoto; // true表示图片，false表示视频

        FileInfo(String filePath, boolean isPhoto) {
            this.filePath = filePath;
            this.isPhoto = isPhoto;
        }
    }

    /**
     * 批量上传文件并提交
     */
    private void uploadFilesAndSubmit(List<FileInfo> filesToUpload, List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                                      List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        ToastUtils.showLongToast("正在上传文件...");

        // 使用队列来按顺序匹配上传结果（因为文件名会改变，无法通过文件名匹配）
        final Queue<FileInfo> uploadQueue = new LinkedList<>(filesToUpload);
        final int[] uploadCount = {0};
        final int totalCount = filesToUpload.size();
        final boolean[] hasError = {false};

        mAccountRequester.getNewFileInfo().observe(this, new Observer<ResponseStatus<WorkOrderDetailBean.FileDto>>() {
            @Override
            public void onChanged(ResponseStatus<WorkOrderDetailBean.FileDto> dataResult) {
                // 检查 Activity 是否还存在
                if (isFinishing() || (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
                    return;
                }

                if (hasError[0]) {
                    return; // 如果已经有错误，不再处理后续结果
                }

                if (dataResult.getResponseCode() == 200) {
                    WorkOrderDetailBean.FileDto uploadedFile = dataResult.getData();
                    if (uploadedFile != null) {
                        // 从队列中取出第一个未匹配的文件（按上传顺序匹配）
                        FileInfo fileInfo = uploadQueue.poll();
                        if (fileInfo != null) {
                            uploadCount[0]++;

                            // 根据文件类型添加到对应列表
                            if (fileInfo.isPhoto) {
                                uploadedPhotos.add(uploadedFile);
                            } else {
                                uploadedVideos.add(uploadedFile);
                            }

                            // 所有文件上传完成
                            if (uploadCount[0] == totalCount) {
                                // 提交数据
                                onSubmit(uploadedPhotos, uploadedVideos);
                            }
                        }
                    } else {
                        hasError[0] = true;
                        if (!isFinishing() && !(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
                            ToastUtils.showLongToast("文件上传失败");
                        }
                    }
                } else {
                    hasError[0] = true;
                    if (!isFinishing() && !(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
                        String errorMsg = dataResult.getMsg();
                        // 检查是否是 HTTP 413 错误（文件太大）
                        if (errorMsg != null && (errorMsg.contains("413") || errorMsg.contains("Request Entity Too Large") || 
                            errorMsg.contains("文件过大") || errorMsg.contains("too large"))) {
                            ToastUtils.showLongToast("文件过大，请选择小于50MB的视频文件");
                        } else if (errorMsg != null && !errorMsg.isEmpty()) {
                            ToastUtils.showLongToast(errorMsg);
                        } else {
                            ToastUtils.showLongToast("文件上传失败");
                        }
                    }
                }
            }
        });

        // 遍历上传每个文件
        for (FileInfo fileInfo : filesToUpload) {
            mAccountRequester.newUploadFile(fileInfo.filePath);
        }
    }

    /**
     * 提交数据
     */
    private void onSubmit(List<WorkOrderDetailBean.FileDto> uploadedPhotos,
                          List<WorkOrderDetailBean.FileDto> uploadedVideos) {
        // 收集表单数据
        String dutyDate = states.dutyDate.get();
        String dutyRecord = getInputText(mBinding.dutyRecordInput);
        String handoverSituation = getInputText(mBinding.handoverSituationInput);

        // 获取项目编码
        String projectCode = UserInfo.getInstance().getProjectCode();
        if (projectCode == null || projectCode.isEmpty()) {
            ToastUtils.showLongToast("无法获取项目信息");
            return;
        }

        // 获取人员对象列表（包含id）
        List<DutyManagerBean.BuSchedulingListBean> dutyPersonList = states.dutyPersonList.get();
        List<DutyManagerBean.BuSchedulingListBean> dutyLeaderList = states.dutyLeaderList.get();
        List<DutyManagerBean.BuSchedulingListBean> receivingPersonList = states.receivingPersonList.get();
        List<DutyManagerBean.BuSchedulingListBean> receivingLeaderList = states.receivingLeaderList.get();

        // 构建JSON请求体
        JsonObject jsonObject = new JsonObject();

        // buProjectDaily对象
        JsonObject buProjectDaily = new JsonObject();
        jsonObject.add("buProjectDaily", buProjectDaily);

        // 其他字段
        jsonObject.addProperty("projectCode", projectCode);
        jsonObject.addProperty("dutyDate", dutyDate != null ? dutyDate : "");

        jsonObject.addProperty("dutyRecords", dutyRecord != null ? dutyRecord : "");
        jsonObject.addProperty("shiftHandover", handoverSituation != null ? handoverSituation : "");
        jsonObject.addProperty("dutyStaff", states.dutyPerson.get() != null ?
                getPersonIdsString(dutyPersonList) : "");
        jsonObject.addProperty("dutyLeader", states.dutyLeader.get() != null ?
                getPersonIdsString(dutyLeaderList) : "");
        jsonObject.addProperty("successor", states.receivingPerson.get() != null ?
                getPersonIdsString(receivingPersonList) : "");
        jsonObject.addProperty("successorLeader", states.receivingLeader.get() != null ?
                getPersonIdsString(receivingLeaderList) : "");

        if (null != uploadedPhotos) {
            // 记录图片列表
            JsonArray recordImgList = new JsonArray();
            for (WorkOrderDetailBean.FileDto photo : uploadedPhotos) {
                if (photo != null && photo.getFilePath() != null) {
                    JsonObject photoObj = new JsonObject();
                    photoObj.addProperty("id", 0);
                    photoObj.addProperty("filePath", photo.getFilePath());
                    photoObj.addProperty("fileName", photo.getFileName() != null ? photo.getFileName() : "");
                    photoObj.addProperty("createTime", "");
                    photoObj.addProperty("createBy", 0);
                    photoObj.addProperty("isDelete", 0);
                    recordImgList.add(photoObj);
                }
            }
            jsonObject.add("imageList", recordImgList);
        }

        if (null != uploadedVideos) {
            // 记录视频列表
            JsonArray recordVideoList = new JsonArray();
            for (WorkOrderDetailBean.FileDto video : uploadedVideos) {
                if (video != null && video.getFilePath() != null) {
                    JsonObject videoObj = new JsonObject();
                    videoObj.addProperty("id", 0);
                    videoObj.addProperty("filePath", video.getFilePath());
                    videoObj.addProperty("fileName", video.getFileName() != null ? video.getFileName() : "");
                    videoObj.addProperty("createTime", "");
                    videoObj.addProperty("createBy", 0);
                    videoObj.addProperty("isDelete", 0);
                    recordVideoList.add(videoObj);
                }
            }
            jsonObject.add("videoList", recordVideoList);
        }

        // 创建RequestBody并调用API
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
        mAccountRequester.saveOrUpdateDutyRecord(requestBody);
    }

    /**
     * 获取人员ID字符串（逗号分隔）
     */
    private String getPersonIdsString(List<DutyManagerBean.BuSchedulingListBean> personList) {
        if (personList == null || personList.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < personList.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(personList.get(i).getId());
        }
        return sb.toString();
    }

    /**
     * 获取输入框文本
     */
    private String getInputText(EditText editText) {
        return editText != null ? editText.getText().toString().trim() : "";
    }

    /**
     * 启动人员选择页面
     */
    private void startPersonnelSelection(String selectionType) {
        currentSelectionType = selectionType;

        Intent intent = new Intent(this, PersonnelSelectionActivity.class);
        intent.putExtra("selectionType", selectionType);

        // 根据选择类型，传递已选中的对象列表和显示名称（用于回显）
        List<DutyManagerBean.BuSchedulingListBean> preselectedItems = new ArrayList<>();
        String preselectedNames = "";
        switch (selectionType) {
            case "dutyPerson":
                if (states.dutyPersonList.get() != null) {
                    preselectedItems = new ArrayList<>(states.dutyPersonList.get());
                }
                preselectedNames = states.dutyPerson.get() != null ? states.dutyPerson.get() : "";
                break;
            case "dutyLeader":
                if (states.dutyLeaderList.get() != null) {
                    preselectedItems = new ArrayList<>(states.dutyLeaderList.get());
                }
                preselectedNames = states.dutyLeader.get() != null ? states.dutyLeader.get() : "";
                break;
            case "handoverPerson":
                if (states.handoverPersonList.get() != null) {
                    preselectedItems = new ArrayList<>(states.handoverPersonList.get());
                }
                preselectedNames = states.handoverPerson.get() != null ? states.handoverPerson.get() : "";
                break;
            case "handoverLeader":
                if (states.handoverLeaderList.get() != null) {
                    preselectedItems = new ArrayList<>(states.handoverLeaderList.get());
                }
                preselectedNames = states.handoverLeader.get() != null ? states.handoverLeader.get() : "";
                break;
            case "receivingPerson":
                if (states.receivingPersonList.get() != null) {
                    preselectedItems = new ArrayList<>(states.receivingPersonList.get());
                }
                preselectedNames = states.receivingPerson.get() != null ? states.receivingPerson.get() : "";
                break;
            case "receivingLeader":
                if (states.receivingLeaderList.get() != null) {
                    preselectedItems = new ArrayList<>(states.receivingLeaderList.get());
                }
                preselectedNames = states.receivingLeader.get() != null ? states.receivingLeader.get() : "";
                break;
        }

        intent.putExtra("preselectedItems", new ArrayList<>(preselectedItems));
        intent.putExtra("preselectedNames", preselectedNames);

        startActivityForResult(intent, REQUEST_CODE_PERSONNEL_SELECTION);
    }

    /**
     * 处理从人员选择页面返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if (requestCode == REQUEST_CODE_PERSONNEL_SELECTION) {
                @SuppressWarnings("unchecked")
                ArrayList<DutyManagerBean.BuSchedulingListBean> selectedItems =
                        (ArrayList<DutyManagerBean.BuSchedulingListBean>) data.getSerializableExtra("selectedItems");
                String selectedNames = data.getStringExtra("selectedNames");

                if (selectedItems != null && currentSelectionType != null) {
                    // 保存对象列表（包含id）
                    ArrayList<DutyManagerBean.BuSchedulingListBean> itemsList = new ArrayList<>(selectedItems);

                    switch (currentSelectionType) {
                        case "dutyPerson":
                            states.dutyPerson.set(selectedNames != null ? selectedNames : "");
                            states.dutyPersonList.set(itemsList);
                            break;
                        case "dutyLeader":
                            states.dutyLeader.set(selectedNames != null ? selectedNames : "");
                            states.dutyLeaderList.set(itemsList);
                            break;
                        case "handoverPerson":
                            states.handoverPerson.set(selectedNames != null ? selectedNames : "");
                            states.handoverPersonList.set(itemsList);
                            break;
                        case "handoverLeader":
                            states.handoverLeader.set(selectedNames != null ? selectedNames : "");
                            states.handoverLeaderList.set(itemsList);
                            break;
                        case "receivingPerson":
                            states.receivingPerson.set(selectedNames != null ? selectedNames : "");
                            states.receivingPersonList.set(itemsList);
                            break;
                        case "receivingLeader":
                            states.receivingLeader.set(selectedNames != null ? selectedNames : "");
                            states.receivingLeaderList.set(itemsList);
                            break;
                    }
                }
            } else if (PhotoPicker.REQUEST_CODE == requestCode) {
                // 处理图片选择结果
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();

                // 获取新选择的图片路径
                for (String path : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(path);
                    photos.add(dto);
                }

                // 将选择的图片传递给MultiPickResultView
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                mBinding.multiPickResultView.onActivityResult(requestCode, resultCode, data);
            } else if (REQUEST_CODE_VIDEO == requestCode) {
                // 处理视频选择结果
                List<String> videoPaths = Matisse.obtainPathResult(data);
                if (videoPaths != null && !videoPaths.isEmpty()) {
                    selectedVideos.clear();
                    // 视频文件大小限制：50MB
                    final long MAX_VIDEO_SIZE = 50 * 1024 * 1024; // 50MB
                    
                    for (String path : videoPaths) {
                        // 检查文件大小
                        java.io.File videoFile = new java.io.File(path);
                        if (!videoFile.exists()) {
                            ToastUtils.showLongToast("视频文件不存在");
                            continue;
                        }
                        
                        long fileSize = videoFile.length();
                        if (fileSize > MAX_VIDEO_SIZE) {
                            // 文件太大，转换为MB显示
                            double sizeInMB = fileSize / (1024.0 * 1024.0);
                            ToastUtils.showLongToast(String.format("视频文件过大（%.2fMB），最大支持50MB，请选择较小的视频", sizeInMB));
                            continue;
                        }
                        
                        WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                        dto.setFilePath(path);
                        selectedVideos.add(dto);
                    }
                    // 更新视频显示
                    updateVideoDisplay();
                }
            }
        }
    }


    /**
     * 打开视频选择器
     */
    private void openVideoPicker() {
        // 检查权限
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 (API 33) 及以上版本使用新的权限
            permissions = new String[]{
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_IMAGES
            };
        } else {
            // Android 13 以下版本使用传统权限
            permissions = new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        }

        boolean checkPermissionFirst = PermissionsUtils.checkPermissionFirst(this, 1004, permissions);
        if (!checkPermissionFirst) {
            ToastUtils.showLongToast("请允许存储权限，否则无法选择视频");
            return;
        }

        Set<MimeType> mimeTypes = MimeType.ofVideo();

        Matisse.from(this)
                .choose(mimeTypes, false)
                .capture(false)  // 不允许直接录制视频（如果需要可以改为true）
                .setSelectedImages(new ArrayList<>())  // 设置空列表，避免影响图片选择状态
                .maxSelectable(1)  // 最多选择1个视频
                .theme(R.style.Matisse_Dracula)  // 暗色主题
                .imageEngine(new com.nsgf.library.matisse.engine.impl.GlideEngine())
                .forResult(REQUEST_CODE_VIDEO);
    }

    /**
     * 更新视频显示
     */
    private void updateVideoDisplay() {
        LinearLayout videoListLayout = mBinding.llVideoList;
        videoListLayout.removeAllViews();
        // 允许子视图超出容器边界显示（重要：确保删除按钮不被裁剪）
        videoListLayout.setClipChildren(false);
        videoListLayout.setClipToPadding(false);

        if (selectedVideos != null && !selectedVideos.isEmpty()) {
            states.hasVideo.set(true);
            // 手动设置视图可见性，确保立即显示
            videoListLayout.setVisibility(View.VISIBLE);

            // 将dp转换为px
            float density = getResources().getDisplayMetrics().density;
            int videoSize = (int) (80 * density); // 80dp，与上传按钮一样大
            int deleteBtnSize = (int) (20 * density); // 20dp
            int playIconSize = (int) (24 * density); // 24dp，播放图标大小
            int marginRight = (int) (10 * density); // 10dp

            for (int i = 0; i < selectedVideos.size(); i++) {
                WorkOrderDetailBean.FileDto video = selectedVideos.get(i);

                // 创建视频预览视图容器
                RelativeLayout videoItemContainer = new RelativeLayout(this);
                RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                containerParams.setMargins(0, 0, marginRight, 0);
                videoItemContainer.setLayoutParams(containerParams);
                // 允许子视图超出容器边界显示（重要：确保删除按钮不被裁剪）
                videoItemContainer.setClipChildren(false);
                videoItemContainer.setClipToPadding(false);

                // 视频缩略图（使用MediaMetadataRetriever加载视频第一帧）
                android.widget.ImageView thumbnail = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams thumbnailParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                thumbnail.setLayoutParams(thumbnailParams);
                thumbnail.setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP);
                thumbnail.setBackgroundResource(R.drawable.bg_upload_button);

                // 使用MediaMetadataRetriever获取视频第一帧作为缩略图
                String videoPath = video.getFilePath();
                if (videoPath != null && !videoPath.isEmpty()) {
                    loadVideoThumbnail(thumbnail, videoPath, videoSize);
                }

                // 播放图标（居中显示）
                android.widget.ImageView playIcon = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams playIconParams = new RelativeLayout.LayoutParams(
                        playIconSize,
                        playIconSize
                );
                playIconParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                playIcon.setLayoutParams(playIconParams);
                playIcon.setImageResource(R.drawable.ic_play_circle_outline_white_48dp);
                playIcon.setBackgroundResource(android.R.color.transparent);

                // 删除按钮 - 放在容器内部，避免被遮挡
                android.widget.ImageView deleteBtn = new android.widget.ImageView(this);
                RelativeLayout.LayoutParams deleteParams = new RelativeLayout.LayoutParams(
                        deleteBtnSize,
                        deleteBtnSize
                );
                deleteParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                deleteParams.addRule(RelativeLayout.ALIGN_PARENT_END);
                // 使用正边距，将删除按钮放在容器内部，距离边缘4dp
                int deleteMargin = (int) (4 * density); // 4dp的正边距，确保在容器内部
                deleteParams.setMargins(0, deleteMargin, deleteMargin, 0);
                deleteBtn.setLayoutParams(deleteParams);
                // 使用正确的删除图标
                deleteBtn.setImageResource(R.drawable.icon_delete);
                deleteBtn.setPadding((int) (2 * density), (int) (2 * density), (int) (2 * density), (int) (2 * density));
                // 设置 elevation 确保在最上层（API 21+）
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    deleteBtn.setElevation(10f * density); // 10dp elevation，确保在最上层
                }
                // 确保可点击
                deleteBtn.setClickable(true);
                deleteBtn.setFocusable(true);
                // 设置内容描述，提高可访问性
                deleteBtn.setContentDescription("删除视频");
                final int index = i;
                deleteBtn.setOnClickListener(v -> {
                    selectedVideos.remove(index);
                    if (selectedVideos.isEmpty()) {
                        states.hasVideo.set(false);
                    }
                    updateVideoDisplay();
                });

                videoItemContainer.addView(thumbnail);
                videoItemContainer.addView(playIcon);
                videoItemContainer.addView(deleteBtn);
                // 确保删除按钮在最上层
                deleteBtn.bringToFront();
                videoListLayout.addView(videoItemContainer);
            }
        } else {
            states.hasVideo.set(false);
            // 手动设置视图不可见，确保立即隐藏
            videoListLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 加载视频缩略图
     */
    private void loadVideoThumbnail(android.widget.ImageView imageView, String videoPath, int size) {
        new Thread(() -> {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(videoPath);
                Bitmap bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                if (bitmap != null) {
                    // 在主线程更新UI
                    runOnUiThread(() -> {
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
                        imageView.setImageBitmap(scaledBitmap);
                        if (scaledBitmap != bitmap) {
                            bitmap.recycle();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e("PatrolActivity", "加载视频缩略图失败: " + e.getMessage());
            } finally {
                try {
                    retriever.release();
                } catch (Exception e) {
                    Log.e("PatrolActivity", "释放MediaMetadataRetriever失败: " + e.getMessage());
                }
            }
        }).start();
    }


    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        Set<MimeType> mimeTypes = new HashSet<>();
        mimeTypes.add(MimeType.JPEG);
        mimeTypes.add(MimeType.PNG);
        mimeTypes.add(MimeType.GIF);

        mBinding.multiPickResultView.init(
                this,
                MultiPickResultView.ACTION_SELECT,  // 用于图片选择
                new ArrayList<WorkOrderDetailBean.FileDto>(),  // 初始图片列表（空）
                9,  // 最大选择数量
                0,  // index
                mimeTypes,
                new PhotoAdapter.PhotoOnClick() {
                    @Override
                    public void setPhotoListener(int position) {

                    }
                }
        );
    }

    public class ClickProxy {

        /**
         * 天气选择
         */
        public void onWeatherClick(int index) {
            selectedWeatherIndex = index;
        }

        /**
         * 选择值班日期
         */
        public void onDutyDateClick() {
            showDatePicker();
        }

        /**
         * 选择交班人员
         */
        public void onHandoverPersonClick() {
            startPersonnelSelection("handoverPerson");
        }

        /**
         * 选择交班领导
         */
        public void onHandoverLeaderClick() {
            startPersonnelSelection("handoverLeader");
        }

        /**
         * 选择值班人员
         */
        public void onDutyPersonClick() {
            startPersonnelSelection("dutyPerson");
        }

        /**
         * 选择值班领导
         */
        public void onDutyLeaderClick() {
            startPersonnelSelection("dutyLeader");
        }

        /**
         * 选择接班人员
         */
        public void onReceivingPersonClick() {
            startPersonnelSelection("receivingPerson");
        }

        /**
         * 选择接班领导
         */
        public void onReceivingLeaderClick() {
            startPersonnelSelection("receivingLeader");
        }

        /**
         * 取消按钮
         */
        public void onCancelClick() {
            finish();
        }

        /**
         * 提交按钮
         */
        public void onSubmitClick() {
            submitUpdate();
        }

        public void onVideoUploadClick() {
            // 打开视频选择器
            openVideoPicker();
        }
    }

    public static class DutyRecordStates extends StateHolder {

        public final State<String> dutyDate = new State<>("");
        public final State<String> waterLevel = new State<>("");
        public final State<Boolean> hasVideo = new State<>(false); // 是否有视频
        public final State<DutyManagerBean> passedRecord = new State<>(new DutyManagerBean());
        public final State<String> dutyRecord = new State<>("");
        public final State<String> handoverSituation = new State<>("");

        // 人员信息（显示名称）
        public final State<String> handoverPerson = new State<>("");
        public final State<String> handoverLeader = new State<>("");
        public final State<String> dutyPerson = new State<>("");
        public final State<String> dutyLeader = new State<>("");
        public final State<String> receivingPerson = new State<>("");
        public final State<String> receivingLeader = new State<>("");

        // 人员列表（包含id信息）
        public final State<List<DutyManagerBean.BuSchedulingListBean>> handoverPersonList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> handoverLeaderList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> dutyPersonList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> dutyLeaderList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> receivingPersonList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> receivingLeaderList = new State<>(new ArrayList<>());
    }
}

